/**
 * Created by kelvin.pang on 2017/6/13.
 */

var Jpang = Jpang||{
    set debug(value) {
        if(!value){
            this.console = {
                info: function(){ },
                warn: function(){ },
                debug: function(){ },
                error: function(){ },
                log: function(){ }
            };
        }else{
            this.console = window.console;
        }
    }
}, P = Jpang, createjs = createjs||{};

Jpang.debug = false;

Jpang.extend = function(Child, Parent) {
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;//super
};

(function (P) {
    'use strict';
    /**
     *
     * @param box
     * @param context
     * @param slider
     * @param parameter
     * @example
         slider(screen2b.s2bBox,
         screen2b.s2bBox.s2bContext,
         screen2b.s2bBox.slider,{
                BOX_H : 441,
                SLIDER_BG_H : 374,
                SLIDER_H : 123,
                CONTENT_H : 915
        });
     */
    P.slider = function(box,context,slider,parameter) {

        var BOX_H,CONTENT_H,CONTENT_INIT_Y,SLIDER_BG_H,SLIDER_H,SLIDER_INIT_Y;
        var propagat,ifpropagat,_f,minY,maxY_slider;

        BOX_H = parameter.BOX_H;
        CONTENT_H = parameter.CONTENT_H;
        CONTENT_INIT_Y = context.y;
        minY =  BOX_H + CONTENT_INIT_Y - CONTENT_H;

        if(slider){
            SLIDER_BG_H = parameter.SLIDER_BG_H;
            SLIDER_H = parameter.SLIDER_H;
            SLIDER_INIT_Y = slider.y;
            _f = (SLIDER_BG_H-SLIDER_H) / (CONTENT_H-BOX_H);
            maxY_slider = SLIDER_BG_H + SLIDER_INIT_Y - SLIDER_H;
        }

        propagat = parameter.propagat || false;
        ifpropagat = true;//滑动到尽头

        box.addEventListener("mousedown",function(evt){
            ifpropagat = CONTENT_INIT_Y != context.y;
            !propagat && ifpropagat && evt.stopPropagation();
            context.offset = {y: context.y - evt.stageY, stageY:evt.stageY};
            if(slider)slider.offset = {y: slider.y , stageY: evt.stageY};
        });
        box.addEventListener("pressmove",function(evt){
            ifpropagat = CONTENT_INIT_Y != context.y;
            !propagat && ifpropagat && evt.stopPropagation();
            if(Math.abs(evt.stageY - context.offset.stageY)>50)box.mouseChildren = false;

            var stepY = evt.stageY + context.offset.y;
            context.y = stepY>CONTENT_INIT_Y ? CONTENT_INIT_Y : stepY<minY ? minY : stepY;

            if(slider){
                var stepY_slider = slider.offset.y + (slider.offset.stageY - evt.stageY) * _f;
                slider.y = stepY_slider<SLIDER_INIT_Y ? SLIDER_INIT_Y : stepY_slider>maxY_slider ? maxY_slider : stepY_slider;
            }
        });
        box.addEventListener("pressup",function(evt){
            !propagat && ifpropagat && evt.stopPropagation();
            box.mouseChildren = true;
        });
    };
    /*P.slider = function(box,context,slider,parameter) {
        var BOX_H = parameter.BOX_H,
            SLIDER_BG_H = parameter.SLIDER_BG_H,
            SLIDER_H = parameter.SLIDER_H,
            CONTENT_H = parameter.CONTENT_H,
            propagat = parameter.propagat || false,
            SLIDER_INIT_Y = slider.y,
            CONTENT_INIT_Y = context.y;
        var F = (SLIDER_BG_H-SLIDER_H) / (CONTENT_H-BOX_H),
            minY =  BOX_H + CONTENT_INIT_Y - CONTENT_H,
            maxY_slider = SLIDER_BG_H + SLIDER_INIT_Y - SLIDER_H;
        box.addEventListener("mousedown",function(evt){
            !propagat && evt.stopPropagation();
            context.offset = {y: context.y - evt.stageY, stageY:evt.stageY};
            slider.offset = {y: slider.y , stageY: evt.stageY};
        });
        box.addEventListener("pressmove",function(evt){
            !propagat && evt.stopPropagation();
            if(Math.abs(evt.stageY - context.offset.stageY)>50){
                box.mouseChildren = false;
            }
            var stepY = evt.stageY + context.offset.y,
                stepY_slider = slider.offset.y + (slider.offset.stageY - evt.stageY) * F;
            context.y = stepY>CONTENT_INIT_Y ? CONTENT_INIT_Y : stepY<minY ? minY : stepY;
            slider.y = stepY_slider<SLIDER_INIT_Y ? SLIDER_INIT_Y : stepY_slider>maxY_slider ? maxY_slider : stepY_slider;
        });
        box.addEventListener("pressup",function(evt){
            !propagat && evt.stopPropagation();
            box.mouseChildren = true;
        });
    };*/
    /**
     * 没滚动条的
     * @param box
     * @param context
     * @param parameter
     */
    /*P.slider2 = function(box,context,parameter) {
        var BOX_H = parameter.BOX_H,
            CONTENT_H = parameter.CONTENT_H,
            propagat = parameter.propagat || false,
            CONTENT_INIT_Y = context.y;
        var minY =  BOX_H + CONTENT_INIT_Y - CONTENT_H;
        box.addEventListener("mousedown",function(evt){
            !propagat && evt.stopPropagation();
            context.offset = {y: context.y - evt.stageY, stageY:evt.stageY};
        });
        box.addEventListener("pressmove",function(evt){
            !propagat && evt.stopPropagation();
            if(Math.abs(evt.stageY - context.offset.stageY)>50){
                box.mouseChildren = false;
            }
            var stepY = evt.stageY + context.offset.y;
            var exY = context.y;
            context.y = stepY>CONTENT_INIT_Y ? CONTENT_INIT_Y : stepY<minY ? minY : stepY;
            parameter.onComplete && parameter.onComplete(context.y-exY);
        });
        box.addEventListener("pressup",function(evt){
            !propagat && evt.stopPropagation();
            box.mouseChildren = true;
        });
    };*/
    /**
     * 获取url中的参数
     * @param name
     * @return {null}
     */
    P.getUrlParam = function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        // if (r != null) return unescape(r[2]); return null; //返回参数值
        if (r != null) return decodeURI(r[2]); return null; //返回参数值
    };
    /**
     * 检查input输入的内容
     * @type {{}}
     */
    P.checkTxt = {
        trim : function(str) {
            return str.replace(/(^\s+)|(\s+$)/g, "");
        },
        name : function(str){
            return this.trim(str).length>0;
        },
        email: function (str) {
            var regex = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
            return this.trim(str).length>0 && regex.test(str);
        },
        phone: function (str) {
            var regex = /^1[0-9]{10}$/;
            return this.trim(str).length>0 && regex.test(str);
        },
        int:function (str) {//正整数
            var regex = /^[0-9]*$/;
            return this.trim(str).length>0 && regex.test(str);
        }
    };

    /**
     * video标签
     * @type {{v: {}, new: new, delect: delect}}
     */
    /*P.video = function(url,parameter){
        parameter = parameter||{};
        this.v = document.createElement('video');
        this.v.src = url;
        for(var i in parameter){
            this.v.setAttribute(i,parameter[i]);
        }
        /!*this.v.setAttribute("src", src);//"http://p.umcgchat.com/520mideavideo.mp4"
        this.v.setAttribute("poster",  parameter.poster||'');//"images/520v.jpg"
        this.v.setAttribute("id", parameter.id||'video');
        this.v.setAttribute("width",  parameter.width||"512");
        this.v.setAttribute("height",  parameter.height||"320");
        this.v.setAttribute("controls",  parameter.controls||"true");
        this.v.setAttribute("preload",  parameter.preload||"auto");
        this.v.setAttribute("x-webkit-airplay", "allow");
        this.v.setAttribute("playsinline", "playsinline");
        this.v.setAttribute("webkit-playsinline", "webkit-playsinline");*!/
        document.body.insertBefore(this.v, document.body.firstChild);
        this.hideVideo = function () {
            this.v.style.display = "none";
            this.v.pause();
        }.bind(this);
        this.showVideo = function () {
            this.v.style.display = "block";
        }.bind(this);
        this.delect = function () {
            this.v && this.v.parentNode.removeChild(this.v);
            this.v = {};
        }
    };*/
    /**
     * 前补 0 操作
     * @param str
     * @param length
     * @return {string}
     */
    P.addZero = function(str,length){
        return length<str.length-1 ? str : (new Array(length - str.length + 1).join("0") + str);
    };

    /**
     * 获取屏幕宽、高
     */
    P.getWidth = function() {
        if( typeof( window.innerWidth ) == 'number' ) {
            return window.innerWidth;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            return document.documentElement.clientWidth;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            return document.body.clientWidth;
        }
    };
    P.getHeight = function() {
        if( typeof( window.innerHeight ) == 'number' ) {
            return window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            return document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            return document.body.clientHeight;
        }
    };

})(Jpang);


/**
 * 注意：要click事件才能触发selectImage, mousedown无法触发
 * @param callback
 * @param _this
 * @example
 selectImage(function(t, imageBase64){
     console.log(t);
     console.log(imageBase64);
 },this);
 */
(function (P) {
    'use strict';
    P.selectImage = function(callback, _this, size) {
        MAX_HEIGHT = size||MAX_HEIGHT;
        selectedHandler = callback;
            thisRef = _this;
        var i = document.getElementById("fileInput");
        null == i && (i = document.createElement("input"),
            i.id = "fileInput",
            i.type = "file",
            i.accept = "image/*",
            i.style.cssText = "height:0px;display:block;overflow:hidden;",
            document.body.insertBefore(i, document.body.firstChild),
            i.addEventListener("change", tmpSelectFile, !1)),
            setTimeout(function() {
                i.click()
            }, 100);
    };
    function tmpSelectFile(e) {
        var file = e.target.files[0], i = file.type;
        i || (i = mime[file.name.match(/\.([^\.]+)$/i)[1]]);
        var n = myCreateObjectURL(file);
        tmpCreateImage(n, file);
        var a = document.getElementById("fileInput");
        a.value = ""
    }
    function tmpCreateImage(url, file) {
        var i = new Image;
        var n = document.createElement("canvas");

        i.onload = function () {
            if(this.width>this.height){
                this.width *= MAX_HEIGHT / this.height, this.height = MAX_HEIGHT;
            }else{
                this.height *= MAX_HEIGHT / this.width, this.width = MAX_HEIGHT;
            }

            getOrientation(file,function (orientation) {
                drawImageHandle(orientation,n,i);
                var base64img = n.toDataURL("image/png");
                i.width = i.height = 1;
                selectedHandler && selectedHandler(thisRef, base64img, file);
            });
        };
        i.src = url;
        i.style.visibility = "hidden";
    }
    function myCreateObjectURL(e) {
        return void 0 != window.URL ? window.URL.createObjectURL(e) : window.webkitURL.createObjectURL(e)
    }
    var mime = {
        png: "image/png",
        jpg: "image/jpeg",
        jpeg: "image/jpeg",
        bmp: "image/bmp"
    }, selectedHandler, thisRef, MAX_HEIGHT = 660;

    /**
     * 获取图片orientation
     * @param file
     * @param callback
     */
    function getOrientation(file,callback) {
        var orientation = null;// 1:0°; 6:顺时针90°; 8:逆时针90°; 3:180°;
        //获取照片方向角属性，用户旋转控制
        try{
            EXIF.getData(file, function() {
                EXIF.getAllTags(this);
                orientation = EXIF.getTag(this, 'Orientation');
                Jpang.console.log('Orientation:',orientation);
                //console.log(EXIF.pretty(this));//打印全部参数
                callback(orientation);
            });
        }catch (e){
            callback(orientation);
            Jpang.console.log(e);
        }
    }
    function drawImageHandle(ori,n,img) {
        var a = n.getContext("2d");
        a.clearRect(0, 0, n.width, n.height);
        var degree;
        switch(ori){
            case 3://180°
                degree = 2*90 * Math.PI / 180;
                n.width = img.width, n.height = img.height,a.rotate(degree), a.drawImage(img, -img.width, -img.height, img.width, img.height);
                break;
            case 6://顺时针90°
                degree = 90 * Math.PI / 180;
                n.width = img.height, n.height = img.width,a.rotate(degree), a.drawImage(img, 0, -img.height, img.width, img.height);
                break;
            case 8://逆时针90°
                degree = 3*90 * Math.PI / 180;
                n.width = img.height, n.height = img.width,a.rotate(degree),a.drawImage(img, -img.width, 0, img.width, img.height);
                break;
            default:
                n.width = img.width, n.height = img.height, a.drawImage(img, 0, 0, img.width, img.height);
        }
    }

})(Jpang);


(function (P,cjs) {
    'use strict';
    /**
     * touch cotroler
     * @type {{enable: Jpang.Touch.enable, disable: Jpang.Touch.disable}}
     */
    P.Touch = {
        enable : function (stage ,allowDefault) {
            cjs.Touch.enable(stage ,false, allowDefault);
            stage.preventSelection = !allowDefault;
        },
        disable : function(stage) {
            cjs.Touch.disable(stage);
        }
    };
    P.nativeEvent = function(evt) {
        evt && evt.nativeEvent && evt.nativeEvent.preventDefault && evt.nativeEvent.preventDefault();
    };
    /**
     * 拍照，控制图片旋转
     * @param callback
     */
    (P.selectImg = function(imageBase64,callback){
        var i = new Image, _this=this;
        this.initialize(i);
        i.onload = function(){
            _this.nominalBounds = new cjs.Rectangle(0, 0,i.width,i.height);
            _this.regX = Math.round(i.width/2);
            _this.regY = Math.round(i.height/2);
            callback && callback();
        };
        // i.setAttribute('crossOrigin', 'anonymous');
        i.src = imageBase64;
    }).prototype = new cjs.Bitmap();

    var bitmap,touchPoint;

    P.actionImg = function(callback,size) {
        P.selectImage(function(t, imageBase64){
            if(bitmap){
                bitmap.removeEventListener("mousedown",imgMouseDown);
                bitmap.removeEventListener("pressmove", imgMouseMove);
                bitmap.removeEventListener("pressup",imgMouseUp);
                bitmap = undefined;
                touchPoint = undefined;
            }
            bitmap = new P.selectImg(imageBase64,function () {
                callback && callback(bitmap);
            });
            // bitmap.y = bitmap.x = size/2;
            bitmap.addEventListener("mousedown",imgMouseDown);
            bitmap.addEventListener("pressmove", imgMouseMove);
            bitmap.addEventListener("pressup",imgMouseUp);
        },this,size);
    };
    var keys, _d, _cd;
    function imgMouseDown(evt) {
        P.nativeEvent(evt);
        touchPoint = touchPoint || {};
        touchPoint[evt.pointerID]={
            x: Math.round(evt.stageX),
            y: Math.round(evt.stageY),
            a : evt,
        };
        bitmap._x = bitmap.x;
        bitmap._y = bitmap.y;
        bitmap._rotation = bitmap.rotation;
        bitmap._scale = bitmap.scaleX;
        keys = Object.keys(touchPoint);
        if(keys.length>1)_d = distance(touchPoint[keys[1]],touchPoint[keys[0]]);
    }

    function imgMouseMove(evt) {
        P.nativeEvent(evt);
        if(!touchPoint)return;
        if(keys.length==1){
            bitmap.x = Math.round(bitmap._x + evt.stageX - touchPoint[evt.pointerID].x);
            bitmap.y = Math.round(bitmap._y + evt.stageY - touchPoint[evt.pointerID].y);
        }else{
            touchPoint[evt.pointerID].a = evt;
            var p1 = {
                    x : touchPoint[keys[1]].a.stageX,
                    y : touchPoint[keys[1]].a.stageY
                },
                p2 = {
                    x:touchPoint[keys[0]].a.stageX,
                    y:touchPoint[keys[0]].a.stageY
                };
            _cd = distance(p1, p2);
            bitmap.scaleX = bitmap.scaleY = bitmap._scale * _cd/_d;
            var v1 = {
                    x : p1.x - p2.x,
                    y : p1.y - p2.y
                },
                v2 = {
                    x : touchPoint[keys[1]].x - touchPoint[keys[0]].x,
                    y : touchPoint[keys[1]].y - touchPoint[keys[0]].y
                };
            var angle = _getRotateAngle(v1, v2);
            bitmap.rotation = bitmap._rotation + angle;
        }
    }
    function imgMouseUp(evt) {
        P.nativeEvent(evt);
        // Jpang.console.log('up');
        if(!touchPoint)return;
        touchPoint = undefined;
    }
    //勾股定理
    function distance(p1,p2){
        var calX = p2.x - p1.x,
            calY = p2.y - p1.y;
        return Math.sqrt(calX * calX + calY * calY);
    }
    //这两个方法属于向量计算
    function _getRotateDirection(vector1,vector2) {
        return vector1.x * vector2.y - vector2.x * vector1.y;
    }
    function _getRotateAngle(vector1,vector2) {
        var direction = _getRotateDirection(vector1,vector2);
        direction = direction > 0 ? -1 : 1;
        var len1 = Math.sqrt(vector1.x*vector1.x + vector1.y*vector1.y);
        var len2 = Math.sqrt(vector2.x*vector2.x + vector2.y*vector2.y);
        var mr = len1 * len2;
        if(mr === 0) return 0;
        var dot = vector1.x * vector2.x + vector1.y * vector2.y;
        var r = dot / mr;
        if(r > 1) r = 1;
        if(r < -1) r = -1;
        return Math.acos(r) * direction * 180 / Math.PI;
    }
})(Jpang,createjs);

/**
 * 调制框
 * 内部必须存在， cls：关闭按钮； scale：调整大小按钮； rotating：角度按钮； box：容器盒子
 * eq:
 * var modu = new P.modulate();
 * modu.init(activeBox,arena,{onClearComplete:onClearMc});
 */
(function (P,cjs) {
    var modulate = function () {
    };
    modulate.prototype = {
        init : function(active,parent,parameter){
            parameter = parameter || {};
            active.visible = false;
            this.parent = parent;
            this.contarner = active;
            this.btnCls = active.cls;
            this.btnScale= active.scale;
            this.btnRotating= active.rotating;
            this.box = active.box;

            var self = this;
            self._enableScale = false;
            self._enableRotation = false;
            self._enableBox = false;

            this.btnCls.addEventListener("mousedown",function (evt) {
                evt.stopPropagation();
                self.contarner.visible = false;
                active.box.removeAllChildren();
                parameter.onClearComplete && parameter.onClearComplete(self._curMc);
                self._curMc = null;
            });

            //listener scale
            this.btnScale.on("mousedown",function (evt) {
                evt.stopPropagation();
                self._enableScale = true;
                self._down(evt);
            });
            this.btnScale.on("pressmove",function (evt) {
                evt.stopPropagation();
                self._move(evt);
            });
            this.btnScale.on("pressup",function (evt) {
                evt.stopPropagation();
                self._enableScale = false;
            });

            //listener rotation
            this.btnRotating.on("mousedown",function (evt) {
                evt.stopPropagation();
                self._enableRotation = true;
                self._down(evt);
            });
            this.btnRotating.on("pressmove",function (evt) {
                evt.stopPropagation();
                self._move(evt);
            });
            this.btnRotating.on("pressup",function (evt) {
                evt.stopPropagation();
                self._enableRotation = false;
            });

            //listener box move
            this.box.on("mousedown",function (evt) {
                evt.stopPropagation();
                self._enableBox = true;
                self._down(evt);
            });
            this.box.on("pressmove",function (evt) {
                evt.stopPropagation();
                self._move(evt);
            });
            this.box.on("pressup",function (evt) {
                evt.stopPropagation();
                self._enableBox = false;

            });
        },
        active : function (mc,index) {
            if(this._curMc)this.box.removeChild(this._curMc);
            this._curMc = mc;
            this.contarner.x = mc.x;
            this.contarner.y = mc.y;
            this.contarner.rotation = mc.rotation;
            this.box.scaleX = mc.scaleX;
            this.box.scaleY = mc.scaleY;
            mc.x = mc.y = mc.rotation = 0;
            mc.scaleX = mc.scaleY = 1;
            this.contarner.visible = true;
            this.box.addChild(mc);
            typeof index == "number" ? this.parent.addChildAt(this.contarner,index) : this.parent.addChild(this.contarner);
            this._draw();
        },
        inactive : function () {
            if(!this._curMc)return;
            this._curMc.x = this.contarner.x;
            this._curMc.y = this.contarner.y;
            this._curMc.rotation = this.contarner.rotation;
            this._curMc.scaleX = this.box.scaleX;
            this._curMc.scaleY = this.box.scaleY;
            var i = this.parent.getChildIndex(this.contarner);
            this.parent.addChildAt(this._curMc, i);
            this.contarner.visible = false;
            this._curMc = null;
        },
        _draw : function(){
            if(!this._g){
                this._g = new cjs.Graphics();
            }
            if(!this._square) {
                this._square = new cjs.Shape(this._g);
                this.contarner.addChild(this._square,this.btnCls,this.btnScale,this.btnRotating);

            }
            var df = 10,
                _scaleX = this.box.scaleX, _scaleY = this.box.scaleY,
                bounds = this.box.getBounds();
            if(!bounds){
                return;
            }
            var _x =_scaleX*(bounds.x-df), _y =_scaleY*(bounds.y-df), _w =_scaleX*(bounds.width+df*2), _h =_scaleY*(bounds.height+df*2);
            this._g.clear();
            this._g.setStrokeStyle(2,"round").beginStroke('#000').drawRect(_x, _y, _w, _h);
            this.btnCls.x = _x;
            this.btnCls.y = _y;
            this.btnScale.x = _x + _w;
            this.btnScale.y = _y + _h;
            this.btnRotating.x = _x + _w;
            this.btnRotating.y = _y;

        },
        _distance :  function (p1, p2) {//勾股定理
            var calX = p2.x - p1.x,
                calY = p2.y - p1.y;
            return Math.sqrt(calX * calX + calY * calY);
        },
        _down : function (evt) {
            var self = this, _x =evt.stageX, _y =evt.stageY;
            if(self._enableBox){
                self.contarner.offset = {
                    x: self.contarner.x - _x,
                    y: self.contarner.y - _y
                };
            }else if(self._enableScale){
                self.box.offset ={
                    distance:self._distance(self.box, self.btnScale),
                    scaleX: self.box.scaleX,
                    scaleY: self.box.scaleY
                };
            }else if(self._enableRotation){
                var p0 = self.parent.globalToLocal(_x, _y);
                self.contarner.offset ={
                    x: p0.x,
                    y: p0.y,
                    rota: self.contarner.rotation
                };
            }
        },
        _move : function (evt) {
            var self = this,
                _x = evt.stageX, _y = evt.stageY;
            if(self._enableBox){
                Jpang.console.log(_x,_y);
                self.contarner.x = _x + self.contarner.offset.x;
                self.contarner.y = _y + self.contarner.offset.y;
            }else if(self._enableScale){
                var d1 = self._distance(self.box, self.contarner.globalToLocal(_x, _y)),
                    d2 = self.box.offset.distance;
                var f = d1/d2;
                Jpang.console.log(d1, d2, f);
                self.box.scaleX = self.box.offset.scaleX * f;
                self.box.scaleY = self.box.offset.scaleX * f;
                this._draw();
            }else if(self._enableRotation){
                var p1 = self.parent.globalToLocal(_x, _y);
                var v1 = {
                        x : p1.x - self.contarner.x,
                        y : p1.y - self.contarner.y
                    },
                    v2 = {
                        x : self.contarner.offset.x - self.contarner.x,
                        y : self.contarner.offset.y - self.contarner.y
                    };
                var angle = self._getRotateAngle(v1, v2);
                Jpang.console.log('angle:',angle);
                self.contarner.rotation = self.contarner.offset.rota + angle;
            }
        },
        //这两个方法属于向量计算
        _getRotateDirection : function (vector1,vector2) {
            return vector1.x * vector2.y - vector2.x * vector1.y;
        },
        _getRotateAngle : function (vector1,vector2) {
            var direction = this._getRotateDirection(vector1,vector2);
            direction = direction > 0 ? -1 : 1;
            var len1 = Math.sqrt(vector1.x*vector1.x + vector1.y*vector1.y);
            var len2 = Math.sqrt(vector2.x*vector2.x + vector2.y*vector2.y);
            var mr = len1 * len2;
            if(mr === 0) return 0;
            var dot = vector1.x * vector2.x + vector1.y * vector2.y;
            var r = dot / mr;
            if(r > 1) r = 1;
            if(r < -1) r = -1;
            return Math.acos(r) * direction * 180 / Math.PI;
        }
    };
    P.modulate = modulate;
})(Jpang,createjs);

/**
 * 手指滑动切换
 * @example
 * eq:
 * var swiper = new Jpang.swiper().init(items,mc1,{direction:'x',span:640,speed:2,loop:false,callback:_call});
 * swiper.goto(0,function (id) {});
 */
(function (P,cjs) {
    'use strict';
    var swiper = function(){};
    swiper.prototype = {
        enable : true,
        space : 80,//触发滑动到下一页的拨动间距
        getIndex : function () {
            return this._index;
        },
        init : function (pages,container,parameter) {
            if(!container)throw new Error('container not undefined.');
            var self = this;
            self._tweenPlay = false;
            self._index=-1;
            self._items = pages || [];
            self._parent = container;
            if(typeof parameter=='object'){
                self._Direction = parameter.direction || 'x';                        //方向
                self._span = parameter.span || 640;                                  //跨度
                self._callback = parameter.callback;                                 //回调方法
                self._speed = parameter.speed || 3;                                  //过场速度
                self._loop = parameter.loop || false;                               //轮回
                self._Type = parameter.type || 'cd';                                 //过场类型。'cd':重叠，'tc':同层平衡
                self._isResetReg = parameter.isResetReg==false?false:true;         //是否重新设置regX|regY
            }
            for(var e in self._items){
                if(self._isResetReg)self._items[e].setTransform(0,0,1,1,0,0,0,0,0);
                self._items[e].visible = false;
                self._items[e].id = e;
            }
            self._index = 0;
            self._activeEventListener();
            return self;
        },
        _activeEventListener : function(){
            var self = this;
            self._parent.addEventListener("mousedown",function (e) {
                P.nativeEvent(e);
                self._downHandle(e);
            });
            self._parent.addEventListener("pressmove",function (e) {
                P.nativeEvent(e);
                self._moveHandle(e);
            });
            self._parent.addEventListener("pressup",function (e) {
                P.nativeEvent(e);
                self._upHandle(e);
            });
        },
        goto : function (id,callback) {
            var self = this;
            if(self._tweenPlay)return;
            var obj = self._items[id];
            self._setPosition(obj,id<self._index ? -self._span : self._span);
            obj.visible = true;
            obj.parent && obj.parent.addChild(obj);
            self._changePage(obj,function (id) {
                callback && callback(id);
                self._callback && self._callback(id);
            });
            self._upObj=self._downObj=undefined;
        },
        _setPosition : function(obj,span) {
            var minShowSpan = 30;
            if(this._Direction=='x'){
                if(minShowSpan<Math.abs(obj.x-span))obj.x=span;
            }else{
                if(minShowSpan<Math.abs(obj.y-span))obj.y=span;
            }
            return 'p'
        },
        _changePage : function(_t,callback){
            var self = this;
            self._tweenPlay = true;

            var ex_obj = self._items[self._index];
            if(_t!=ex_obj && this._Type=='tc'){   //隐藏上一页
                var _val = _t.id< self._index ? self._span :  -self._span;
                var _o = self._Direction=='x'?{x: _val}:{y: _val};
                cjs.Tween.get(ex_obj).to(_o, self._span/self._speed,cjs.Ease.sineOut);
            }
            //onFinish 当前页面转为不活动状态要处理的方法
            if(typeof self._items[self._index].onFinish == 'function' && _t.id != self._index){
                self._items[self._index].onFinish();
            }
            if(typeof _t.net === 'object' && _t.id != self._index){
                _t.net.refresh();
            }
            var _callback=function(p){
                if(_t!=ex_obj)ex_obj.visible = false; //隐藏上一页
                self._index = Number(p);
                if(callback)callback(self._index);
                if(typeof _t.onStart == 'function'){
                    _t.onStart();
                }
                self._tweenPlay = false;
            };
            var o = self._Direction=='x'?{x: 0}:{y: 0};
            cjs.Tween.get(_t).to(o, self._span/self._speed,cjs.Ease.sineOut).call(_callback,[_t.id]);
            return 'c';
        },

        _downHandle : function(evt){
            var self = this;
            if(!self.enable)return;
            if(self._index==-1|| self._tweenPlay)return;

            self._initSpan = self._Direction=='x'?evt.stageX:evt.stageY;

            var up,down;
            if(self._loop){
                up = self._index==0 ? self._items.length-1 : self._index-1;
                down = self._index>= self._items.length-1 ? 0 : self._index+1;
            }else{
                up = self._index - 1;
                down = self._index + 1;
            }
            if(up>=0){
                self._upObj = self._items[up];
                self._setPosition(self._upObj,-self._span);
                self._upObj.visible = true;
                self._upObj.gotoAndStop(0);
                self._upObj.parent && self._upObj.parent.addChild(self._upObj);
            }
            if(down<self._items.length){
                self._downObj = self._items[down];
                self._setPosition(self._downObj,self._span);
                self._downObj.visible = true;
                self._downObj.gotoAndStop(0);
                self._downObj.parent && self._downObj.parent.addChild(self._downObj);
            }
            if(self._Type=='tc'){
                var target = self._items[self._index];
                target.offset = {x: target.x - evt.stageX, y: target.y - evt.stageY};
            }
        },
        _moveHandle : function(evt){
            var self = this;
            if(self._index==-1|| self._tweenPlay)return;

            var _d;
            var XY = self._Direction=='x'?evt.stageX:evt.stageY;
            if(typeof self._upObj!='undefined'){
                _d = XY - self._initSpan - self._span;
                _d = _d>0 ? 0 : _d;
                self._setPosition(self._upObj, _d);
            }
            if(typeof self._downObj!='undefined'){
                _d = XY - self._initSpan + self._span;
                _d = _d<0 ? 0 : _d;
                self._setPosition(self._downObj, _d);
            }
            /*if(XY>self._initSpan){
                if(typeof self._upObj=='undefined')return;
                _d = XY - self._initSpan - self._span;
                _d = _d>0 ? 0 : _d;
                self._setPosition(self._upObj, _d);
            }else{
                if(typeof self._downObj=='undefined')return;
                _d = XY - self._initSpan + self._span;
                _d = _d<0 ? 0 : _d;
                self._setPosition(self._downObj, _d);
            }*/
            if(self._Type=='tc'){
                var target = self._items[self._index];
                self._Direction=='x'? target.x = target.offset.x + XY : target.y = target.offset.y + XY;
            }
            //判断是点击还是滑动
            if(Math.abs(XY - self._initSpan)>self.space){
                self._parent.mouseChildren = false;
            }
        },
        _upHandle: function(){
            var self = this;
            self._parent.mouseChildren = true;
            if(self._index==-1|| self._tweenPlay)return;
            var xy, z, up=false, down=false;
            if(typeof self._upObj!='undefined'){
                xy = self._Direction=='x'?self._upObj.x:self._upObj.y;
                z = xy>self.space-self._span ? self._changePage(self._upObj,self._callback) : self._setPosition(self._upObj, -self._span);
                up = (z=='c');
                self._upObj = undefined;
            }
            if(typeof self._downObj!='undefined'){
                xy = self._Direction=='x'?self._downObj.x:self._downObj.y;
                z = xy<(self._span-self.space) ? self._changePage(self._downObj,self._callback) : self._setPosition(self._downObj, self._span);
                down = (z=='c');
                self._downObj = undefined;
            }
            if(self._Type=='tc'){
                var target = self._items[self._index];
                var value = up? self._span : down? -self._span : 0;
                var o = self._Direction=='x'?{x: value}:{y: value};
                cjs.Tween.get(target).to(o, self._span/self._speed,cjs.Ease.sineOut);
            }
        }
    };
    P.swiper = swiper;

    var swiper2 = function(){};
    P.extend(swiper2, swiper);
    swiper2.prototype._activeEventListener = function(){
        var self = this;
        document.addEventListener("touchstart",function (e) {
            self._downHandle({stageX:e.touches[0].clientX, stageY:e.touches[0].clientY});
        },false);
        document.addEventListener("touchmove",function (e) {
            self._moveHandle({stageX:e.touches[0].clientX, stageY:e.touches[0].clientY});
        },false);
        document.addEventListener("touchend",function (e) {
            self._upHandle();
        },false);
    };
    P.swiper2 = swiper2;

})(Jpang,createjs);

/**
 * @example
 * mainBGM = new AudioCreate("media/bgm.mp3?1514713110064",{id:"bgm"});
 */
(function (P) {
    'use strict';
    P.AudioCreate = function (src,param) {
        var aud = document.createElement('audio');
        param = param || {};
        param.id && (aud.id=param.id);
        aud.src=src;
        aud.preload="auto";
        aud.controls=true;
        aud.hidden=true;
        // if(param.autoplay)aud.autoplay = true;
        aud.autoplay = true;
        if(param.loop!=false){
            aud.onended = function() {
                aud.currentTime=0;
                aud.play();
            };
        }

        if (typeof WeixinJSBridge === "undefined") {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        }
        onBridgeReady();
        function onBridgeReady() {
            aud.play();
            /*if(param.autoplay==false) {
                var t = setTimeout(function () {
                    clearTimeout(t);
                    aud.pause();
                });
            }*/
        }

        var isPause = param.autoplay==false;
        var _playingHandle = function () {
            if(isPause)aud.pause();
        };
        aud.addEventListener("playing",_playingHandle);

        this.stop = function () {
            isPause = true;
            if(aud.readyState>1 && !aud.paused){
                aud.pause();
            }
        };
        this.play = function (time) {
            isPause = false;
            if(typeof time=='number')aud.currentTime=time;
            aud.play();
        };
        this.delete = function () {
            this.stop();
            document.removeEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            aud.removeEventListener("playing",_playingHandle);
            aud=null;
            param=null;
            src=null;
        };
        this.audio = aud;
    };
})(Jpang);

/**
 * 地图控制器
 * @param map
 * @param param
 * @constructor
 * @example
 * var MapContr = new Jpang.MapControler(map,{map_width:2734,map_height:2000,c_width:canvasWidth,c_height:canvasHeight});
 */
Jpang.MapControler = function (map,param) {

    //是否属于触发地图热点
    // this.hasHotEvent = true;
    var touchPoint, keys, _d, _cd;
    var map_width = param.map_width||100,
        map_height = param.map_height||100,
        c_width = param.c_width||100,
        c_height = param.c_height||100;
    // var THIS = this;
    map.on('mousedown', mapMouseDown);
    map.on('pressmove', mapMouseMove);
    map.on('pressup', function (evt) {
        evt.stopPropagation();
        P.nativeEvent(evt);

        delete touchPoint[evt.pointerID];
        keys = Object.keys(touchPoint);
        if (keys.length == 0) {
            //恢复触发热点事件
            map.mouseChildren = true;
            touchPoint = undefined;
            var maxW = map_width * this.scaleX,//this.nominalBounds.width
                maxH = map_height * this.scaleY;//this.nominalBounds.height
            this.x = this.x > maxW / 2 ? maxW / 2 : this.x < c_width - maxW / 2 ? c_width - maxW / 2 : this.x;
            this.y = this.y > maxH / 2 ? maxH / 2 : this.y < c_height - maxH / 2 ? c_height - maxH / 2 : this.y;
        }
    });
    /*map.x = map.regX = this.nominalBounds.width/2;
    map.y = map.regY = this.nominalBounds.height/2;*/
    map.initScale = 0.6;//map.scaleX;
    // mcGo.mcM.map.setTransform(0,0,1,1,0,0,0,0,0);
    // Jpang.console.log('x:',mcGo.mcM.map.x,'  y:',mcGo.mcM.map.y,'  w:',mcGo.mcM.map.nominalBounds.width*mcGo.mcM.map.scaleX,' scale:',mcGo.mcM.map.scaleX);

    function mapMouseDown(evt) {
        P.nativeEvent(evt);
        // evt.stopPropagation();
        // Jpang.console.log('down');
        touchPoint = touchPoint || {};
        touchPoint[evt.pointerID] = {
            x: Math.round(evt.stageX),
            y: Math.round(evt.stageY),
            a: evt
        };
        this.offset = {x: this.x, y: this.y, rotation: this.rotation, scale: this.scaleX};
        keys = Object.keys(touchPoint);
        if (keys.length > 1) {
            _d = distance(touchPoint[keys[1]], touchPoint[keys[0]]);
            map.mouseChildren = false; //放大动作就默认不是触发热点事件
        }
    }

    function mapMouseMove(evt) {
        evt.stopPropagation();
        P.nativeEvent(evt);
        // Jpang.console.log('moveeeeeeeeeeee');
        if (!touchPoint)return;
        if (keys.length == 1) {
            var _x = Math.round(this.offset.x + evt.stageX - touchPoint[evt.pointerID].x);
            var _y = Math.round(this.offset.y + evt.stageY - touchPoint[evt.pointerID].y);
            var maxW = map_width * this.scaleX,//this.nominalBounds.width
                maxH = map_height * this.scaleY;//this.nominalBounds.height
        } else {
            touchPoint[evt.pointerID].a = evt;
            var p1 = {
                    x: touchPoint[keys[1]].a.stageX,
                    y: touchPoint[keys[1]].a.stageY
                },
                p2 = {
                    x: touchPoint[keys[0]].a.stageX,
                    y: touchPoint[keys[0]].a.stageY
                };
            /*var L1 = this.globalToLocal(p1.x,p1.y);
             var L2 = this.globalToLocal(p2.x,p2.y);*/

            _cd = distance(p1, p2);
            this.scaleX = this.scaleY = Math.max(this.offset.scale * _cd / _d, this.initScale);


            _x = this.x, _y = this.y;

        }
        this.x = _x > maxW / 2 ? maxW / 2 : _x < c_width - maxW / 2 ? c_width - maxW / 2 : _x;
        this.y = _y > maxH / 2 ? maxH / 2 : _y < c_height - maxH / 2 ? c_height - maxH / 2 : _y;
        // Jpang.console.log(this.x,'  ',this.y,'  ',this.globalToLocal(evt.stageX,evt.stageY).x*this.scaleX);

        //触发位移距离大于20就默认不是触发热点事件
        if(Math.abs(_x - this.offset.x) >= 40 || Math.abs(_y - this.offset.y) >= 40){
            map.mouseChildren = false;
        }
        // if (Math.abs(_x - this.offset.x) >= 20 || Math.abs(_y - this.offset.y) >= 20)THIS.hasHotEvent = false;
    }

    //勾股定理
    function distance(p1, p2) {
        var calX = p2.x - p1.x,
            calY = p2.y - p1.y;
        return Math.sqrt(calX * calX + calY * calY);
    }
};

(function (P,cjs) {
    "use strict";

    function DisplayDocument(type,w,h,t,l) {
        this.doc = document.createElement(type);//"img"、"input"、"textarea"、"video"
        this._width = w;
        this._height = h;
        this._top = t;
        this._left = l;
        var cssText = 'padding:0; margin:0; position:absolute; z-index:999; border:none; display:none; ';
        cssText += 'height:' + this._height +'px;';
        cssText += 'width:' + this._width +'px;';
        cssText += 'top:' + this._top +'px;';
        cssText += 'left:' + this._left +'px;';
        this.doc.style.cssText += cssText;
    }
    DisplayDocument.prototype = {
        get value(){
            return this.doc.value;
        },
        set value(val){
            this.doc.value = val;
        }
    };
    DisplayDocument.prototype.show = function () {
        this.doc.style.display= 'block';
    };
    DisplayDocument.prototype.hide = function () {
        this.doc.style.display= 'none';
    };
    DisplayDocument.prototype.resize = function (canvas) {
        //获取document标签缩放后的实际宽高,位置等信息
        var rect = canvas.getBoundingClientRect();
        var wf = rect.width/canvas.width, hf = rect.height/canvas.height;
        var cssText = 'height:' + (this._height * hf) +'px;';
        cssText += 'width:' + (this._width * wf) +'px;';
        cssText += 'top:' + ((this._top * hf) +rect.top) +'px;';
        cssText += 'left:' + ((this._left * wf) +rect.left) +'px;';
        this.doc.style.cssText += cssText;
    };

    function Text(type,txt,param) {
        if(!(txt instanceof cjs.Text))throw new Error("txt type must is cjs.Text!");
        var param = param||{};
        var fonts = txt.font.split("px "),//"26px 'Adobe Heiti Std R'"
            bounds = txt.getBounds();
        var p1 = txt.parent.localToGlobal(txt.x,txt.y);
        var w = txt.lineWidth,
            h = param.height || txt.lineHeight,
            t = p1.y +bounds.y -txt.regY,
            l = p1.x +bounds.x -txt.regX;
            if(txt.textAlign=="center")
            l -= (w - bounds.width)/2;
        DisplayDocument.call(this,type,w,h,t,l); //super();
        this._fontSize = fonts[0];
        this.doc.value = param.value||'';
        this.doc.placeholder = param.placeholder||'';
        // txt.text = '';
        if(param.native && typeof param.native=='object'){
            for(var i in param.native) {
                if(Object.prototype.hasOwnProperty.call(param.native,i)) { //过滤
                    this.doc.setAttribute(i,param.native[i]);//添加标签属性
                }
            }
        }//end if

        var cssText = 'background:transparent; outline:none; ';
        cssText += 'color:'+ txt.color;
        cssText += ';font-family:'+ fonts[1];
        cssText += ';font-size:' + this._fontSize +'px;';
        cssText += 'text-align:' + txt.textAlign +';';
        this.doc.style.cssText += cssText;

        txt = null;
        param = null;
    }
    P.extend(Text,DisplayDocument);
    Text.prototype.resize = function (canvas) {
        DisplayDocument.prototype.resize.call(this,canvas);
        var rect = canvas.getBoundingClientRect();
        var hf = rect.height/canvas.height;
        this.doc.style.fontSize = this._fontSize * hf +'px';
    };

    /**
     * 根据createjs Text对象生成对应document input标签
     * @type {Text}
     * @example
     *  var input = new P.InputText(exportRoot.txt,canvas,{type:"text",placeholder:'input content',
	 		native:{maxlength:11, onkeyup:"this.value=this.value.replace(/[^0-9]/g,'')", onafterpaste:"this.value=this.value.replace(/[^0-9]/g,'')"}
	 	});
     */
    P.InputText = function (cjsTxt,canvas, param) {
        param = param||{};
        Text.call(this,'input',cjsTxt,param);
        param.type && (this.doc.type = param.type);
        this.resize(canvas);
        this.doc.style.cssText += param.cssText||'';
        canvas.parentNode.insertBefore(this.doc, canvas.parentNode.firstChild);
    };
    P.extend(P.InputText,Text);
    P.InputText.prototype.resize = function (canvas) {
        Text.prototype.resize.call(this,canvas);
        var rect = canvas.getBoundingClientRect();
        var hf = rect.height/canvas.height;
        var cssText = 'line-height:' + (this._height * hf) +'px;';
        this.doc.style.cssText += cssText;
    };

    /**
     * 根据createjs Text对象生成对应document select标签
     * @param cjsTxt
     * @param canvas
     * @param param
     * var select = new P.SelectText(exportRoot.txt,canvas)
     */
    P.SelectText = function (cjsTxt,canvas, param) {
        param = param||{};
        Text.call(this,'select',cjsTxt,param);
        this.resize(canvas);
        this.doc.style.cssText += param.cssText||'';
        canvas.parentNode.insertBefore(this.doc, canvas.parentNode.firstChild);
    };
    P.extend(P.SelectText,Text);

    /**
     * 根据createjs Text对象生成对应document textarea标签
     * @type {Text}
     * @example
     * new P.Textarea(exportRoot.txt2,canvas,{height:191,placeholder:'textarea content'});
     */
    P.Textarea = function (cjsTxt,canvas, param) {
        param = param||{};
        Text.call(this,'textarea',cjsTxt,param);
        this.resize(canvas);
        this.doc.style.cssText += "resize:none" + param.cssText||'';
        canvas.parentNode.insertBefore(this.doc, canvas.parentNode.firstChild);
    };
    P.extend(P.Textarea,Text);

    /**
     * 根据createjs MovieClip对象生成对应document img标签
     * @type {Text}
     * @example
     * new P.QRcode(qrcodeobj,canvas,{src:'qrcode.jpg'});
     */
    P.QRcode = function(obj,canvas,param) {
        // if(!(obj instanceof cjs.Bitmap))throw new Error("obj type must is cjs.Bitmap!");
        param = param||{};
        var bounds = obj.getBounds();
        var p1 = obj.parent.localToGlobal(obj.x,obj.y);
        var w = bounds.width,
            h = param.height || bounds.height,
            t = p1.y +bounds.y -obj.regY,
            l = p1.x +bounds.x -obj.regX;
        DisplayDocument.call(this,"img",w,h,t,l); //super();
        this.doc.src = param.src;
        obj = null;
        param = null;
        canvas.parentNode.insertBefore(this.doc, canvas.parentNode.firstChild);
        this.resize(canvas);
    };
    P.extend(P.QRcode,DisplayDocument);

    /**
     * 根据createjs MovieClip对象生成对应document button标签
     * @param obj
     * @param canvas
     * @param param
     * @constructor
     */
    P.Button = function(obj,canvas,param) {
        param = param||{};
        var bounds = obj.getBounds();
        var p1 = obj.parent.localToGlobal(obj.x,obj.y);
        var w = bounds.width,
            h = param.height || bounds.height,
            t = p1.y +bounds.y -obj.regY,
            l = p1.x +bounds.x -obj.regX;
        DisplayDocument.call(this,"button",w,h,t,l); //super();
        obj = null;
        param = null;
        canvas.parentNode.insertBefore(this.doc, canvas.parentNode.firstChild);
        this.resize(canvas);
    };
    P.extend(P.Button,DisplayDocument);

    /**
     * 根据createjs MovieClip对象生成对应document video标签
     * @type {Text}
     * @example
     * new P.video(qrcodeobj,canvas,{src:'qrcode.jpg'});
     */
    P.video = function(obj,canvas,param) {
        param = param||{};
        var bounds = obj.getBounds();
        var p1 = obj.parent.localToGlobal(obj.x,obj.y);
        var w = bounds.width,
            h = param.height || bounds.height,
            t = p1.y +bounds.y -obj.regY,
            l = p1.x +bounds.x -obj.regX;
        DisplayDocument.call(this,"video",w,h,t,l); //super();
        param = param||{};
        this.doc.src = param.src;
        this.doc.style.cssText += param.cssText||'';
        for(var i in param.attribute){
            this.doc.setAttribute(i,param.attribute[i]);
        }
        obj.visible = false;
        obj = null;
        param = null;
        this.resize(canvas);
        canvas.parentNode.insertBefore(this.doc, canvas.parentNode.firstChild);
        this.hide = function () {
            this.doc.style.display= 'none';
            this.doc.pause();
        }
    };
    P.extend(P.video,DisplayDocument);

})(Jpang,createjs);